/**
 * Copyright (C) 2011-2012 Luca Li Greci
 *
 * This file is part of pojo-creator
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.pojocreator.provider.collection;

import java.util.Arrays;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;

import com.pojocreator.provider.DataProvider;

/**
 * This abstract class provides the basic functionality to access the given
 * collection of elements, whereas its sub classes specify how the element is
 * returned.
 * 
 * @author Luca Li Greci
 * @param <T> Data type to provide
 */
public abstract class AbstractFromCollection < T > implements DataProvider < T > {
    // Identified as Visibility Modifier issue by checkstyle.  
    //CHECKSTYLE:OFF
    protected List < T > values;
    //CHECKSTYLE:ON

    /**
     * Creates a DataProvider using the element in the collection.
     * 
     * @param values array of elements type T.
     */
    public AbstractFromCollection(T... values) {
        if (values != null) {
            this.values = Arrays.asList(values);
        }
    }

    /**
     * This method returns an element from the array of elements passed in.
     * <p>
     * <b>N.B.</b> This method can return null if the array of element is null
     * or empty.
     * 
     * @return an element from the array.
     */
    @Override
	public abstract T data();

    /**
     * Return the type of element managed in the collection.
     * 
     * @return The type of element managed is <code>Class < T ></code> or null
     *         if the collection is empty.
     */
    @SuppressWarnings("unchecked")
    @Override
    public Class < T > type() {
        Class < T > type = null;
        if (CollectionUtils.isEmpty(values)) {
            return type;
        }
        T t = values.get(0);
        return (Class < T >) t.getClass();
    }

    /**
     * The number of elements returned in the underly collection.
     * 
     * @return number of elements returned in the collection.
     */
    @Override
    public int size() {
        return values.size();
    }

}
